<template>
  <div class="file-upload">
    <div class="upload-list">
      <!-- 已上传的文件列表 -->
      <div v-for="(file, index) in fileList" :key="index" class="upload-item">
        <!-- 图片预览 -->
        <img v-if="file.type === 'image'" :src="file.url" class="upload-preview" />
        <!-- 视频预览 -->
        <video v-else-if="file.type === 'video'" :src="file.url" class="upload-preview" controls></video>
        <!-- 文件信息 -->
        <div v-else class="file-info">
          <el-icon><Document /></el-icon>
          <span class="file-name">{{ file.name }}</span>
        </div>
        
        <!-- 操作按钮 -->
        <div class="upload-actions">
          <el-button v-if="file.type !== 'image' && file.type !== 'video'" size="small" @click="downloadFile(file)">
            <el-icon><Download /></el-icon>
          </el-button>
          <el-button size="small" type="danger" @click="removeFile(index)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
      
      <!-- 添加按钮 -->
      <div v-if="fileList.length < maxCount" class="upload-add" @click="triggerUpload">
        <el-icon><Plus /></el-icon>
        <span>{{ addText }}</span>
      </div>
    </div>
    
    <!-- 隐藏的文件输入 -->
    <input 
      ref="fileInputRef" 
      type="file" 
      :accept="accept" 
      multiple 
      style="display: none" 
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadFile } from '@/api/system'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  type: {
    type: String,
    default: 'image', // image, video, file
    validator: (value) => ['image', 'video', 'file'].includes(value)
  },
  maxCount: {
    type: Number,
    default: 5
  },
  maxSize: {
    type: Number,
    default: 10 * 1024 * 1024 // 10MB
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const fileInputRef = ref()

// 文件列表
const fileList = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 接受的文件类型
const accept = computed(() => {
  switch (props.type) {
    case 'image':
      return 'image/*'
    case 'video':
      return 'video/*'
    case 'file':
      return '*/*'
    default:
      return '*/*'
  }
})

// 添加按钮文本
const addText = computed(() => {
  switch (props.type) {
    case 'image':
      return '添加图片'
    case 'video':
      return '添加视频'
    case 'file':
      return '添加文件'
    default:
      return '添加文件'
  }
})

// 触发文件选择
const triggerUpload = () => {
  fileInputRef.value.click()
}

// 处理文件选择
const handleFileChange = async (event) => {
  const files = Array.from(event.target.files)
  if (files.length === 0) return
  
  for (const file of files) {
    if (fileList.value.length >= props.maxCount) {
      ElMessage.warning(`最多只能上传${props.maxCount}个文件`)
      break
    }
    
    // 检查文件大小
    if (file.size > props.maxSize) {
      ElMessage.error(`文件 ${file.name} 超过最大大小限制`)
      continue
    }
    
//    try {
      const res = await uploadFile(file, props.type)
      let newUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + res.fileNames
      const newFile = {
        url: newUrl,
        filename: res.filename,
        name: file.name,
        type: props.type,
        size: file.size
      }
      
      fileList.value.push(newFile)
      emit('change', fileList.value)
//    } catch (error) {
//      ElMessage.error(`文件 ${file.name} 上传失败`)
//    }
  }
  
  // 清空input
  event.target.value = ''
}

// 删除文件
const removeFile = (index) => {
  fileList.value.splice(index, 1)
  emit('change', fileList.value)
}

// 下载文件
const downloadFile = (file) => {
  const link = document.createElement('a')
  link.href = file.url
  link.download = file.name
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<style scoped>
.file-upload {
  width: 100%;
}

.upload-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 10px;
}

.upload-item {
  position: relative;
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  transition: all 0.3s;
}

.upload-item:hover {
  border-color: #409eff;
}

.upload-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
}

.upload-add {
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  color: #999;
}

.upload-add:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-add .el-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.upload-add span {
  font-size: 12px;
}

/* 文件项样式 */
.file-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  padding: 10px;
  text-align: center;
}

.file-name {
  font-size: 12px;
  color: #333;
  word-break: break-all;
  line-height: 1.2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-item,
  .upload-add {
    width: 100px;
    height: 100px;
  }
  
  .upload-list {
    gap: 10px;
  }
}
</style> 